package com.xuxueli.applyModules.controller;
import com.google.common.collect.Lists;
import com.xuxueli.applyModules.anotation.InterfaceOperateLog;
import com.xuxueli.applyModules.anotation.NoRepeatSubmit;
import com.xuxueli.applyModules.entity.User;
import com.xuxueli.applyModules.utils.ResourceUtil;
import com.xuxueli.applyModules.utils.exporttables.TestDoc;
import com.xuxueli.applyModules.utils.testcharts.ExportWordUtils;
import com.xuxueli.applyModules.utils.testcharts.PdfUtil3;
import com.xuxueli.applyModules.utils.testcharts.WordUtil;
import com.xuxueli.applyModules.utils.testcreateword.FreeMarkerUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/word")
@Api(tags = "导出word")
@Slf4j
public class WordExportController {

    private static final String pathfile = "Daytemplate.docx";

    /**
     * 通过本地模板导出word文档
     * @param response
     */
    @GetMapping("/export")
    public void wordExport(HttpServletResponse response) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", "年终总结大会");
        data.put("place", "第一会议室");
        data.put("time", "2021年3月25日");
        data.put("sponsor", "张三");
        List<User> users = Lists.newArrayList(
                new User("张三", "组织部", "10:00"),
                new User("李四", "宣传部", "10:00"));
        data.put("userList", users);
        FreeMarkerUtil.createLocalDoc(data, response);
    }

    /**
     * 下载模板
     * @param response
     */
    @ApiOperation("下载模板")
    @GetMapping("/download")
    public void downloadTemplate(HttpServletResponse response) {
        try {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/msword");
//            response.setHeader("Content-disposition", "attachment;filename=" + new String("会议签到表".getBytes("utf-8"), "ISO8859-1"));
            response.reset();
            response.setCharacterEncoding("utf-8");
            System.out.println(ResourceUtil.getcontentType(pathfile));
            response.setContentType(ResourceUtil.getcontentType(pathfile));
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(pathfile, "UTF-8"));
            ResourceUtil.downloadDocument(pathfile, response.getOutputStream());
        } catch (IOException e) {
            log.error("下载失败: {}", pathfile);
        }
    }

    /**
     * 导出Word的PDF
     * @param response
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "limit", value = "每页显示条数", dataType = "Integer"),
            @ApiImplicitParam(name = "currPage", value = "当前页码", dataType = "Integer")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "OK", response = void.class)})
    @ApiOperation(value = "导出Word的PDF")
    @GetMapping(value = "/exportWordPDF", produces = "application/octet-stream")
    public void exportWord( HttpServletResponse response) {
        Map<String,Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("cartType", "身份证二代");
        String filepath = PdfUtil3.exportWord("template/test.docx", "swxxPDF/", "生成文件.docx", map);
        PdfUtil3.convertDocx2Pdf(filepath, "898", "张三");
        try {
            PdfUtil3.downloadFile(response, "898", "张三");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出word
     * @param response
     */
    @GetMapping("PoiWord")
    @ApiOperation(value = "导出word",notes = "导出word")
    public void PoiWord(HttpServletResponse response){
        XWPFDocument document= new XWPFDocument();
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("41");
        try {
            // 这里写你在数据库中查出的数据
            for (String str:list){
                //添加标题
                XWPFParagraph titleParagraph = document.createParagraph();
                XWPFRun titleParagraphRun = titleParagraph.createRun();
                titleParagraphRun.setText("汇报人：苌"+str);
                XWPFParagraph titleParagraph1 = document.createParagraph();
                XWPFRun titleParagraphRun1 = titleParagraph1.createRun();
                titleParagraphRun1.setText("提交状态：按时完成"+str);
                XWPFParagraph titleParagraph2 = document.createParagraph();
                XWPFRun titleParagraphRun2 = titleParagraph2.createRun();
                titleParagraphRun2.setText("汇报内容: "+str);
                //段落
                XWPFParagraph firstParagraph = document.createParagraph();
                XWPFRun run = firstParagraph.createRun();
                run.setText("安静地被罚款敬爱的师父那订房的哈弗连接吧断开连接你疯啦等会呢弗兰克敬爱的很舒服柯兰多爱上的看法较好的快交付拉山东矿机奋达科技暗示分离爱上的看法建安大口径卡掉数据返回阿斯顿开飞机has");
                run.setColor("000000");//设置字体颜色
                run.setFontSize(10);//设置字体大小
                //换行
                XWPFParagraph paragraph3 = document.createParagraph();
                XWPFRun paragraphRun3 = paragraph3.createRun();
                paragraphRun3.setText("\r");//此处换行符无用 代码实际作用为新增一行插入内容为空
            }
            SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
            String fileName = new String("word导出".getBytes("UTF-8"), "iso-8859-1");
            new WordUtil().exportWord(document,response,fileName+sdf.format(new Date()));
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("导出成功！！！！");
    }

    /**
     * 生成word并下载
     * @param request
     * @param response
     */
    @ApiOperation(value = "hahah")
    @PostMapping("/demo/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> params = new HashMap<>();
        params.put("username","这是标题");
        params.put("substatus","哈哈");
        params.put("subtime","了咯哦");
        params.put("zhouqi","讷讷");
        params.put("neirong","iiik");
        //InputStream is = this.getClass().getResourceAsStream("/word/export.docx");
        ClassPathResource resource = new ClassPathResource("export.docx");
        InputStream is = null;
        try {
            is = resource.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExportWordUtils.exportWord(is,"D:/data","aaa.docx",params,request,response);
    }

    /**
     * 下载word
     * @param response
     */
    @ApiOperation("下载word")
    @GetMapping("/downlWord")
    @NoRepeatSubmit(lockTime = 2000L)
    @InterfaceOperateLog(type = "B",content = "B下载word")
    public void downloadTemplateWord(HttpServletResponse response) {
        try {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/msword");
//            response.setHeader("Content-disposition", "attachment;filename=" + new String("会议签到表".getBytes("utf-8"), "ISO8859-1"));
            response.reset();
            response.setCharacterEncoding("utf-8");
            System.out.println(ResourceUtil.getcontentType("你好.doc"));
            response.setContentType(ResourceUtil.getcontentType("你好.doc"));
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode("你好.doc", "UTF-8"));
            String exportDoc = TestDoc.exportDoc("D:\\data\\你好.doc");
            ResourceUtil.downloadFile(exportDoc, response.getOutputStream());
        } catch (IOException e) {
            log.error("下载失败: {}", pathfile);
        }
    }

}
